package com.easywork.mystery.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easywork.mystery.entity.MsgComm;
import com.easywork.mystery.entity.MsgInfo;
import com.easywork.mystery.entity.SysUser;
import com.easywork.mystery.repository.MsgCommRepository;
import com.easywork.mystery.repository.MsgInfoRepository;

@Transactional
@Service
public class MsgCommService {
	@Autowired
	private MsgCommRepository msgcommRepository;

	@Autowired
	private MsgInfoRepository msginfoRepository;

	public MsgCommRepository getMsgCommRepository() {
		return msgcommRepository;
	}

	// --发邮件
	public void saveMail(SysUser usersend, SysUser userRecevier, String title, String content) {
		Date createtime = new Date();
		// --保存邮件信息
		MsgInfo msgInfo = new MsgInfo();
		msgInfo.setCreatetime(createtime);
		msgInfo.setState(1);
		msgInfo.setContent(content);
		msgInfo.setTitle(title);
		MsgInfo saveInfo = msginfoRepository.save(msgInfo);
		// --保存发件人和收件人信息
		MsgComm msgComm = new MsgComm();
		msgComm.setCreatetime(createtime);
		msgComm.setMsgId(saveInfo.getId());
		msgComm.setMsgTitle(title);
		msgComm.setReadflag(0);
		msgComm.setReceiverId(userRecevier.getId());
		msgComm.setReceiverAccount(userRecevier.getAccount());
		msgComm.setSenderId(usersend.getId());
		msgComm.setSenderAccount(usersend.getAccount());
		msgComm.setState(1);
		msgcommRepository.save(msgComm);
	}

	// -- 查看所有邮件,state=1的显示,不为1的不显示
	public Page<MsgComm> findAll(SysUser user, Pageable pageable) {
		MsgComm msgComm = new MsgComm();
		msgComm.setReceiverId(user.getId());
		msgComm.setState(1);
		Example<MsgComm> example = Example.of(msgComm);
		return msgcommRepository.findAll(example, pageable);
	}

	// --根据id查看该条数据
	public MsgComm findById(Long id) {
		MsgComm msgComm = msgcommRepository.findOne(id);
		msgComm.setReadflag(1);
		return msgComm;
	}

	public void delById(Long id) {
		msgcommRepository.delete(id);
	}

	// -- 改已读为未读
	public void saveMsgComm(MsgComm msgComm) {
		msgcommRepository.save(msgComm);
	}

	// -- 假删除,修改state=0
	public void deleteAll(SysUser user) {
		List<MsgComm> msgComms = findAll(user);
		for (MsgComm msgComm : msgComms) {
			msgComm.setState(0);
			msgcommRepository.save(msgComm);
		}
	}

	// -- 查看所有邮件
	public List<MsgComm> findAll(SysUser user) {
		MsgComm msgComm = new MsgComm();
		msgComm.setReceiverId(user.getId());
		return msgcommRepository.findAll(Example.of(msgComm));
	}
}